<template>
  <div class="box" :class="{ 'add-class-content': !flag }">
    <div ref="content" class="content">
      <img
        class="login-img images"
        :class="{
          'add-class-login-img': !flag,
          'add-class-login-img-show': flag,
        }"
        src="../../assets/login.jpg"
        alt="登录"
      />
      <div ref="loginWrapper" class="login-wrapper">
        <div class="top-tips">
          <div class="title">
            {{ $t("login.title") }}
            <lang-select class="set-language" />
          </div>
          <!-- <span class="top-tips-span" @click="toggleForm">{{ topLabel }}</span> -->
        </div>
        <h1>{{ titleLabel }}</h1>

        <div v-if="flag" class="login-form">
          <div>
            <el-form
              ref="loginFormRef"
              :model="loginForm"
              :rules="loginRules"
              auto-complete="on"
              label-position="left"
            >
              <el-form-item prop="username" class="form-item">
                <el-input
                  ref="username"
                  :prefix-icon="User"
                  v-model="loginForm.username"
                  :placeholder="$t('login.username')"
                  name="username"
                  type="text"
                  tabindex="1"
                  auto-complete="on"
                />
              </el-form-item>
              <el-tooltip
                :disabled="capslockTooltipDisabled"
                content="大写锁定开启"
                placement="right"
              >
                <el-form-item prop="password" class="form-item">
                  <el-input
                    ref="passwordRef"
                    :prefix-icon="Lock"
                    :key="passwordType"
                    v-model="loginForm.password"
                    :type="passwordType"
                    placeholder="Password"
                    name="password"
                    tabindex="2"
                    auto-complete="on"
                    @keyup="checkCapslock"
                    @blur="capslockTooltipDisabled = true"
                    @keyup.enter="handleLogin"
                  >
                    <template #suffix>
                      <span class="show-pwd" @click="showPwd">
                        <el-icon
                          v-if="passwordType === 'password'"
                          class="el-input__icon"
                          ><Hide
                        /></el-icon>
                        <el-icon v-else class="el-input__icon"
                          ><View
                        /></el-icon>
                      </span>
                    </template>
                  </el-input>
                </el-form-item>
              </el-tooltip>

              <div class="login-bottom">
                <el-button
                  size="large"
                  :loading="loading"
                  type="primary"
                  @click.prevent="handleLogin"
                  >{{ $t("login.login") }}
                </el-button>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, reactive, ref, toRefs, watch } from "vue";
import LangSelect from "@/components/LangSelect/index.vue";
import { LoginData } from "@/api/auth/types";
import router from "@/router";
// import SvgIcon from '@/components/SvgIcon/list.vue';
import { Lock, User, View, Hide, UserFilled } from "@element-plus/icons-vue";
// 状态管理依赖
import { useRoute } from "vue-router";
import { ElForm, ElInput } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
import { getCurrentInstance } from "vue";
import { genFileId } from "element-plus";
import type {
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadRequestOptions,
} from "element-plus";
import { uploadFileApi } from "@/api/file";
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const {
  appContext: {
    config: {
      globalProperties: { $t },
    },
  },
} = getCurrentInstance()!; // 这里可以根据需要写个hook
const permissionStore = useUserStoreHook();
const upload = ref<UploadInstance>();
const route = useRoute();
const handleUploadAvatar: UploadProps["onExceed"] = (files) => {
  upload.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  console.log(genFileId());
  upload.value?.handleStart(file);
};
const loginFormRef = ref(ElForm);
const registerFormRef = ref(ElForm);
const passwordRef = ref(ElInput);
const password_confirmRef = ref(ElInput);

function validatePassword(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error($t("login.validatePassword")));
  } else {
    callback();
  }
}

function validateUsername(rule: any, value: any, callback: any) {
  if (value.length === 0) {
    callback(new Error($t("login.validateUsername")));
  } else {
    callback();
  }
}

const state = reactive({
  avatarUrl: "",
  redirect: "",
  loginForm: {
    username: "root", // test
    password: "123456",
  } as LoginData,

  password_confirm: "",
  loginRules: {
    username: [{ required: true, trigger: "blur" }],
    nickname: [{ required: true, trigger: "blur" }],
    mobile: [{ required: true, trigger: "blur" }],
    password: [
      { required: true, trigger: "blur", validator: validatePassword },
    ],
  },

  loading: false,
  passwordType: "password",
  password_confirmType: "password",
  // 大写提示禁用
  capslockTooltipDisabled: true,
  otherQuery: {},
  clientHeight: document.documentElement.clientHeight,
});

const {
  loginForm,
  loginRules,
  loading,
  passwordType,
  password_confirmType,
  capslockTooltipDisabled,
  avatarUrl,
} = toRefs(state);

function checkCapslock(e: any) {
  const { key } = e;
  // state.capslockTooltipDisabled =
  //   key && key.length === 1 && key >= 'A' && key <= 'Z';
  if (key === "CapsLock") {
    console.log("CapsLock");
    state.capslockTooltipDisabled = false;
  } else {
    state.capslockTooltipDisabled = true;
  }
  console.log(capslockTooltipDisabled.value);
}

function showPwd() {
  if (state.passwordType === "password") {
    state.passwordType = "";
  } else {
    state.passwordType = "password";
  }
  nextTick(() => {
    passwordRef.value.focus();
  });
}

function showPwdConfirm() {
  if (state.password_confirmType === "password") {
    state.password_confirmType = "";
  } else {
    state.password_confirmType = "password";
  }
  nextTick(() => {
    password_confirmRef.value.focus();
  });
}

function handleLogin() {
  console.log(import.meta.env.VITE_APP_SYSTEM_API);
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      state.loading = true;
      permissionStore
        .login(state.loginForm)
        .then(() => {
          router.push({ path: state.redirect || "/", query: state.otherQuery });
          state.loading = false;
        })
        .catch(() => {
          state.loading = false;
        });
    } else {
      return false;
    }
  });
}

const uploadAvatar = async (options: UploadRequestOptions): Promise<any> => {
  console.log(options.file);
  const { data: fileInfo } = await uploadFileApi(options.file);
  console.log(fileInfo);
  avatarUrl.value = fileInfo.url;
};

const flag = ref(true);
const content = ref();
const loginWrapper = ref();

const topLabel = computed(() => {
  return flag.value ? $t("login.register") : $t("login.login");
});
const titleLabel = computed(() => {
  return flag.value ? $t("login.login") : $t("login.register");
});
const toggleForm = async () => {
  state.passwordType = "password";
  await nextTick();
  if (flag.value) {
    loginWrapper.value.style.height = "85vh";
    content.value.style.height = "90vh";
  } else {
    loginWrapper.value.style.height = "70vh";
    content.value.style.height = "85vh";
  }
  flag.value = !flag.value;
};
watch(
  route,
  () => {
    const query = route.query;
    if (query) {
      state.redirect = query.redirect as string;
      state.otherQuery = getOtherQuery(query);
    }
  },
  {
    immediate: true,
  }
);

function getOtherQuery(query: any) {
  return Object.keys(query).reduce((acc: any, cur: any) => {
    if (cur !== "redirect") {
      acc[cur] = query[cur];
    }
    return acc;
  }, {});
}
</script>

<style lang="scss" scoped>
* {
  padding: 0;
  margin: 0;
}

.box {
  width: 100vw;
  height: 100vh;
  background-color: rgb(51 32 108);

  .content {
    position: absolute;
    top: 50%;
    left: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90vw;
    height: 85vh;
    overflow: hidden;
    background-color: rgb(228 218 232);
    border-radius: 40px;
    transition: 1s;
    transform: translate(-50%, -50%);

    .images {
      position: absolute;
      left: 15%;
      margin-right: 100px;
      margin-left: -150px;
    }

    .login-img {
      width: 45%;
      height: 90%;
      border-radius: 15%;
    }

    .register-img {
      width: 45%;
      border-radius: 15%;
      opacity: 0;
    }

    .login-wrapper {
      position: absolute;
      right: 10%;
      box-sizing: border-box;
      width: 30vw;
      height: 70vh;
      padding: 60px;
      background: rgb(244 240 245 / 60%);
      border-radius: 40px;
      transition: 1s;
      backdrop-filter: blur(1px);

      .top-tips {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title {
          display: flex;
          margin-right: 20px;
          font-size: 26px;
          font-weight: bold;
          text-align: center;

          .set-language {
            margin: auto 10px;
            font-size: 20px;
            cursor: pointer;
          }
        }

        .top-tips-span {
          float: right;
          font-size: 15px;
          line-height: 25px;
          color: rgb(79 133 226);
          cursor: pointer;
          border-bottom: 1px solid rgb(79 133 226);
        }
      }

      h1 {
        margin: 20px 0;
        font-size: 45px;
      }

      .register-form {
        width: 100%;

        .form-item {
          margin-bottom: 20px;

          .text-tips {
            margin: 5px;
            color: rgb(123 122 123);

            .forgot-password {
              float: right;
              font-size: 15px;
              line-height: 25px;
              color: rgb(79 133 226);
              cursor: pointer;
              border-bottom: 1px solid rgb(79 133 226);
            }
          }

          input {
            box-sizing: border-box;
            width: 100%;
            height: 50px;
            padding: 0 20px;
            margin: 5px 0;
            font-size: 17px;
            border: 0;
            border-radius: 5px;
          }

          input:focus {
            border: 1px solid rgb(79 133 226);
            outline: none;
          }
        }
      }

      .login-form {
        .form-item {
          margin-bottom: 20px;
        }

        .login-bottom {
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
}

.add-class-content {
  background-color: rgb(156 148 208) !important;
  transition: 0.1s;
}

.add-class-login-img {
  animation: disappear 0.3s forwards;
  animation-timing-function: ease;
}

.add-class-login-img-show {
  animation: appear 0.5s forwards;
  animation-timing-function: ease;
  animation-delay: 0.5s;
}

.add-class-register-img {
  animation: appear 0.5s forwards;
  animation-timing-function: ease;
  animation-delay: 0.2s;
}

@keyframes appear {
  from {
    border-radius: 15%;
    opacity: 0;
  }

  to {
    border-radius: 0;
    opacity: 1;
  }
}

@keyframes disappear {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}
</style>
<style lang="scss" scoped>
.el-input {
  height: 40px;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
}

.el-input__icon {
  font-size: 20px;
  cursor: pointer;
}

.el-button {
  width: 150px;
  height: 40px;
  font-size: 20px;
  color: #fff;
  cursor: pointer;
  background-color: rgb(59 58 59);
  border: 0;
  border-radius: 5px;
}
</style>
